# -*- coding: utf-8 -*-
"""
pytest配置文件
包含测试的全局配置、fixtures和工具函数
"""

import pytest
import asyncio
import sys
import os
from pathlib import Path
from typing import Generator, AsyncGenerator, Dict, Any
from httpx import AsyncClient
from fastapi.testclient import TestClient

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from app.main import app
from app.core.config import settings
from tests.utils.test_client import APITestClient
from utils.config import get_config
from utils.logger import get_logger

# Allure配置已移动到根目录conftest.py

# 配置日志
logger = get_logger(__name__)

# Allure相关配置
os.environ.setdefault("ALLURE_RESULTS_DIR", "allure-results")
os.environ.setdefault("ALLURE_REPORT_DIR", "allure-report")


@pytest.fixture(scope="session")
def event_loop():
    """创建事件循环"""
    loop = asyncio.get_event_loop_policy().new_event_loop()
    yield loop
    loop.close()


@pytest.fixture(scope="function")
def test_client() -> Generator[TestClient, None, None]:
    """
    创建FastAPI测试客户端
    每个测试函数都会创建新的客户端实例
    """
    with TestClient(app) as client:
        yield client


@pytest.fixture(scope="function")
async def async_client() -> AsyncGenerator[AsyncClient, None]:
    """
    创建异步HTTP客户端
    用于测试异步接口
    """
    async with AsyncClient(app=app, base_url="http://test") as client:
        yield client


@pytest.fixture(scope="function")
def api_client() -> APITestClient:
    """
    创建API测试客户端
    封装了常用的测试方法和断言
    """
    return APITestClient(base_url="http://localhost:8000")


@pytest.fixture(scope="function")
def test_user_data():
    """测试用户数据"""
    import uuid
    unique_id = str(uuid.uuid4())[:8]
    return {
        "name": f"张三_{unique_id}",
        "email": f"zhangsan_{unique_id}@example.com",
        "age": 25
    }


@pytest.fixture(scope="function")
def update_user_data():
    """更新用户数据"""
    import uuid
    unique_id = str(uuid.uuid4())[:8]
    return {
        "name": f"李四_{unique_id}",
        "email": f"lisi_{unique_id}@example.com",
        "age": 30
    }


@pytest.fixture(scope="function")
def invalid_user_data():
    """无效用户数据"""
    return {
        "name": "",  # 空名称
        "email": "invalid-email",  # 无效邮箱
        "age": -1  # 无效年龄
    }


@pytest.fixture(autouse=True)
async def cleanup_users():
    """
    自动清理测试数据
    每个测试执行前后都会清理用户数据
    """
    # 测试前清理 - 使用API端点中的同一个user_service实例
    from app.api.v1.endpoints.users import user_service
    await user_service.clear_all_users()
    
    yield
    
    # 测试后清理
    await user_service.clear_all_users()


@pytest.fixture(scope="session")
def test_settings():
    """测试环境配置"""
    settings.TESTING = True
    return settings


# pytest标记定义
pytestmark = pytest.mark.asyncio